<template>
	<!-- 选择 -->
	<Top-Page class="options-box">
		<NavBar
			:title="title"
			leftText="返回"
			:rightText="rightText"
			@click-left="navBack()"
			@click-right="onClickRight"
			style="box-shadow: none; border-bottom: 1rpx solid #d6d6d6"
		></NavBar>

		<scroll-view
			scroll-y
			class="scroll-view"
			:scroll-into-view="'scroll-view-' + listCurID"
			:style="[{ height: 'calc(100vh - ' + (CustomBar + inlineTools + StatusBar) + 'px)' }]"
			:scroll-with-animation="true"
			:enable-back-to-top="true"
		>
			<view
				class="label-box"
				v-if="['remind', 'invisible', 'visible'].includes(query.type)"
			>
				<view class="label-title">标签</view>

				<checkbox-group>
					<view class="label-list-box">
						<view
							class="label-item"
							v-for="(item, index) in label_list"
							:key="'label_list' + index"
							@click.stop="checkboxChange(item, 'label')"
						>
							<checkbox
								@click.stop="checkboxChange(item, 'label')"
								:value="item.label_id"
								:checked="item.checked"
							/>
							<view class="label-item-right">
								<view class="label-item-title">
									<view class="label-item-title__text text-one">
										{{ item.title }}
									</view>
									<view class="label-item-num">（{{ item.num }}）</view>
								</view>

								<view
									class="label-item-introduce text-one"
									v-if="item.friend && item.friend.length"
								>
									<template v-for="it in item.friend"
										>{{ it.realname }}&nbsp;</template
									>
								</view>
							</view>
						</view>
					</view>
				</checkbox-group>
			</view>

			<view class="contacts-list">
				<checkbox-group>
					<view
						class="contacts-item-wrap border-bottom-after"
						v-for="(item, index) in contacts"
						:key="index"
					>
						<view class="padding" :id="'scroll-view-' + item.name"
							>{{ item.name }}</view
						>
						<view
							class="contacts-item"
							v-for="(it, ind) in item.children"
							@click.stop="checkboxChange(it, 'individual')"
						>
							<checkbox
								v-if="!selected_list.includes(String(it.user_id)) && query.type != 'radio'"
								:value="it.user_id"
								:checked="it.checked"
								@click.stop="checkboxChange(it, 'individual')"
							/>
							<view class="contacts-item-right border-bottom-after">
								<image :src="it.avatar" class="contacts-it-avatar" />
								{{ it.displayName || it.realname }}
							</view>
						</view>
					</view>
				</checkbox-group>
			</view>
		</scroll-view>

		<view
			class="indexBar"
			:style="[{ height: 'calc(100vh - ' + CustomBar + 'px - 50px)' }]"
		>
			<view class="indexBar-box" @touchstart="tStart" @touchend="tEnd">
				<view
					class="indexBar-item"
					v-for="(item, index) in contacts"
					:key="index"
					:id="index"
					@touchstart="getCur"
					@touchend="setCur"
				>
					{{ item.name || item.realname }}
				</view>
			</view>
		</view>

		<!--选择显示-->
		<view v-show="!hidden" class="indexToast"> {{ listCur }} </view>
	</Top-Page>
</template>

<script>
	import NavBar from "@/components/NavBar/NavBar.vue";
	import { navBack } from "@/utils/utils.js";
	import pinia from "@/store/index";
	import { storeToRefs } from "pinia";
	import { useFriendStore } from "@/store/friend.js";
	import { useMsgStore } from "@/store/message";
	const friendStore = useFriendStore(pinia);
	const msgStore = useMsgStore(pinia);
	const { contacts, sysUnread } = storeToRefs(msgStore);

	export default {
		data() {
			return {
				navBack: navBack,
				LabelUsersStore: friendStore.labelUsers,
				query: {},
				title: "",
				rightText: "完成",
				label_list: [],
				selected_list: [], //曾经已经选择过的用户，添加时就不能再被选中了
				contacts: [],
				msgs: contacts,
				hidden: true,
				listCur: "",
				listCurID: "",
				checkbox_list: {
					individual: [],
					label: [],
				},
			};
		},
		components: { NavBar },
		onLoad(options) {
			Object.assign(this.query, options);

			this.selected_list = options.addList ? options.addList.split(",") : [];

			this.rightText = options.type === "radio" ? "" : "完成";

			this.title =
				options.type == "add" || options.type == "new"
					? "添加好友"
					: options.type == "cut"
					? "删除好友"
					: options.type == "remind"
					? "提醒谁看"
					: options.type == "visible"
					? "谁可见"
					: options.type == "invisible"
					? "谁不可见"
					: "选择好友";

			options.type == "cut"
				? this.contacts.push(...this.LabelUsersStore)
				: this.firstApi();
		},
		mounted() {},
		methods: {
			checkboxChange(it, type) {
				if (this.selected_list.includes(String(it.user_id))) {
					return;
				}

				if (this.query.type === "radio") {
					friendStore.changeCardName({
						avatar: it.avatar,
						realname: it.realname,
						user_id: it.user_id,
					});
					this.navBack();
				} else {
					const index = this.checkbox_list[type].indexOf(it);

					index == -1
						? this.checkbox_list[type].push(it)
						: this.checkbox_list[type].splice(index, 1);
					it.checked = !it.checked;
				}
			},
			firstApi() {
				this.disposeContacts();

				this.$api.friendCircleApi.imLabel().then((res) => {
					this.label_list.length = 0;

					this.label_list.push(...(res.data ?? []));
				});
			},
			//处理联系人
			disposeContacts() {
				//联系人
				const allContacts = JSON.parse(JSON.stringify(this.msgs));
				const contacts = allContacts.filter((item) => {
					return item.is_group == 0;
				});

				// 将联系人进行排序
				const sorted = contacts.sort((a, b) => {
					if (a.index === "#") {
						return 1;
					}
					if (b.index === "#") {
						return -1;
					}

					return a.index.localeCompare(b.index, "zh");
				});

				// 重组联系人
				const result = sorted.reduce((acc, cur) => {
					const index = cur.index;
					const existingIndex = acc.findIndex((item) => item.name === index);
					if (existingIndex === -1) {
						acc.push({ name: index, children: [cur] });
					} else {
						acc[existingIndex].children.push(cur);
					}

					return acc;
				}, []);

				this.contacts = result;
			},
			setCur(e) {
				this.hidden = true;
				this.listCur = this.listCur;
			},
			//获取文字信息
			getCur(e) {
				this.hidden = false;

				this.listCur = this.contacts[e.target.id].name;
			},
			//触发全部开始选择
			tStart() {
				this.hidden = false;
			},
			//触发结束选择
			tEnd() {
				this.hidden = true;
				this.listCurID = this.listCur;
			},
			//修改标签内的成员
			changeLabel(friends) {
				const data = {
					friend: friends,
					type: this.query.type == "add" ? 1 : 2,
					label_id: this.query.id,
				};

				this.$api.friendCircleApi.changeLabelUser(data).then((res) => {
					uni.showToast({
						title: `${res.msg}`,
						icon: "none",
					});

					res.code == 0 && this.navBack();
				});
			},
			//添加标签
			addLabel(friends) {
				const data = {
					friend: friends,
					title: this.query.name,
				};

				this.$api.friendCircleApi.labelAdd(data).then((res) => {
					uni.showToast({
						title: `${res.msg}`,
						icon: "none",
					});

					if (res.code == 0) {
						uni.redirectTo({
							url: `/pages/friend/details-label/details-label?id=${res.data.label_id}&title=${this.query.name}`,
						});
					}
				});
			},
			//右上角的完成
			onClickRight() {
				let friends = [];

				if (["add", "cut", "new"].includes(this.query.type ?? "")) {
					if (!this.checkbox_list.individual.length) {
						uni.showToast({
							title: "请选择添加的成员",
							icon: "none",
						});
						return;
					}

					friends = this.checkbox_list.individual.map((item) => item.user_id);
				}

				if (this.query.type == "new") {
					this.addLabel(friends);
				} else if (["add", "cut"].includes(this.query.type ?? "")) {
					this.changeLabel(friends);
				} else if (["remind"].includes(this.query.type)) {
					friendStore.changeRemindObjList(this.checkbox_list);

					uni.redirectTo({
						url: "/pages/friend/release-dynamic/release-dynamic",
					});
				} else if (["invisible", "visible"].includes(this.query.type)) {
					friendStore.changeFiltrate(this.checkbox_list);

					uni.redirectTo({
						url: "/pages/friend/release-dynamic/release-dynamic",
					});
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>
